<template>
  <div class="meeting-management management-page">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filterForm" class="search-form">
        <el-form-item label="会议类型">
          <el-select v-model="filterForm.type" placeholder="全部类型" style="width: 130px">
            <el-option label="全部类型" :value="MeetingType.ALL" />
            <el-option
              v-for="type in meetingTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="会议状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" style="width: 130px">
            <el-option label="全部状态" :value="null" />
            <el-option label="草稿" :value="MeetingStatus.DRAFT" />
            <el-option label="未开始" :value="MeetingStatus.NOT_STARTED" />
            <el-option label="进行中" :value="MeetingStatus.IN_PROGRESS" />
            <el-option label="已结束" :value="MeetingStatus.FINISHED" />
            <el-option label="已取消" :value="MeetingStatus.CANCELLED" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 320px"
          />
        </el-form-item>

        <el-form-item label="关键词">
          <el-input
            v-model="filterForm.keyword"
            placeholder="搜索会议名称/地点"
            clearable
            :prefix-icon="Search"
            @keyup.enter="handleSearch"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>      </el-form>
    </el-card>

    <!-- 会议列表 -->
    <el-card class="list-card" shadow="never" v-loading="loading" element-loading-text="加载中...">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span class="header-title">会议列表</span>
            <el-tag type="info" class="header-count" size="small">
              共 {{ total }} 条
            </el-tag>
          </div>
          <el-space>
            <el-button type="primary" :icon="Plus" @click="handleAdd">
              新增会议
            </el-button>
            <el-tooltip :content="selectedMeetings.length ? '导出选中的会议' : '请先选择要导出的会议'" placement="top">
              <el-button
                type="success"
                :icon="Download"
                @click="handleExport"
                :disabled="!selectedMeetings.length"
              >
                导出数据 {{ selectedMeetings.length ? `(${selectedMeetings.length})` : '' }}
              </el-button>
            </el-tooltip>
            <el-tooltip :content="selectedMeetings.length ? '删除选中的会议' : '请先选择要删除的会议'" placement="top">
              <el-button
                type="danger"
                :icon="Delete"
                @click="handleBatchDelete"
                :disabled="!selectedMeetings.length"
              >
                批量删除 {{ selectedMeetings.length ? `(${selectedMeetings.length})` : '' }}
              </el-button>
            </el-tooltip>
          </el-space>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="meetingList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        border
        stripe
        highlight-current-row
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="name" label="会议名称" min-width="200" show-overflow-tooltip fixed="left">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              {{ row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="coverImage" label="封面图" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.coverImage"
              :src="row.coverImage"
              :preview-src-list="[row.coverImage]"
              fit="cover"
              class="cover-image"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="会议描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tooltip
              :content="row.description"
              placement="top"
              :hide-after="0"
            >
              <span>{{ row.description }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="会议类型" width="120">
          <template #default="{ row }">
            <el-tag type="success" effect="dark" size="small">
              {{ getMeetingTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="会议状态" width="100">
          <template #default="{ row }">
            <meeting-status-tag :status="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="会议时间" width="300">
          <template #default="{ row }">
            <el-tooltip :content="formatDate(row.begin) + ' 至 ' + formatDate(row.end)" placement="top">
              <span>{{ formatDate(row.begin) }} 至 {{ formatDate(row.end) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="会议地点" width="150" show-overflow-tooltip />
        <el-table-column label="会议形式" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isOnline ? 'success' : 'info'" size="small">
              {{ row.isOnline ? '线上' : '线下' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="相关文件" width="100" align="center">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              @click="handleViewFiles(row)"
            >
              查看文件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="点击量" width="100" align="center">
          <template #default="{ row }">
            <el-tooltip content="浏览次数" placement="top">
              <div class="count-item">
                <el-icon><View /></el-icon>
                {{ parseInt(row.browseCount || '0') }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="点赞量" width="100" align="center">
          <template #default="{ row }">
            <el-tooltip content="点赞次数" placement="top">
              <div class="count-item">
                <el-icon><Star /></el-icon>
                {{ parseInt(row.goodCount || '0') }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="agenda" label="议程" min-width="300">
          <template #default="{ row }">
            <div v-if="row.agenda" class="agenda-list">
              <div v-for="(item, index) in JSON.parse(row.agenda)" :key="index" class="agenda-item">
                <span class="agenda-time">{{ item.startTime }} - {{ item.endTime }}</span>
                <span class="agenda-title">{{ item.title }}</span>
                <span class="agenda-speaker">主讲人：{{ item.speaker }}</span>
                <span class="agenda-description">{{ item.description }}</span>
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="videoUrl" label="视频" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.videoUrl"
              type="primary"
              link
              @click="handleViewVideo(row)"
            >
              查看视频
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button 
                v-if="row.status === MeetingStatus.DRAFT"
                type="success" 
                link 
                :icon="Upload" 
                @click="handlePublish(row)"
              >
                发布
              </el-button>
              <el-button 
                type="primary" 
                link 
                :icon="Edit" 
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                link 
                :icon="Delete" 
                @click="handleDelete(row)"
              >
                删除
              </el-button>
              <el-button
                v-if="row.status === MeetingStatus.NOT_STARTED"
                type="warning"
                link
                :icon="CircleClose"
                @click="handleCancel(row)"
              >
                取消
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑会议对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增会议' : '编辑会议'"
      width="40%"
      destroy-on-close
    >
      <meeting-form
        :meeting="currentMeeting"
        @submit="handleSubmit"
        @cancel="dialogVisible = false"
      />
    </el-dialog>

    <!-- 会议详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="会议详情"
      width="80%"
    >
      <template v-if="currentMeeting">
        <div class="meeting-detail">
          <div class="detail-header">
            <h2>{{ currentMeeting.name }}</h2>
            <meeting-status-tag :status="currentMeeting.status" />
          </div>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="会议类型">
              {{ getMeetingTypeLabel(currentMeeting.type) }}
            </el-descriptions-item>
            <el-descriptions-item label="会议地点">
              {{ currentMeeting.location }}
            </el-descriptions-item>
            <el-descriptions-item label="开始时间">
              {{ formatDate(currentMeeting.begin) }}
            </el-descriptions-item>
            <el-descriptions-item label="结束时间">
              {{ formatDate(currentMeeting.end) }}
            </el-descriptions-item>
            <el-descriptions-item label="是否线上">
              <el-tag :type="currentMeeting.isOnline ? 'success' : 'info'" size="small">
                {{ currentMeeting.isOnline ? '线上' : '线下' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="会议描述" :span="2">
              {{ currentMeeting.description }}
            </el-descriptions-item>
            <el-descriptions-item label="会议议程" :span="2">
              <pre>{{ currentMeeting.agenda }}</pre>
            </el-descriptions-item>
            <el-descriptions-item v-if="currentMeeting.videoUrl" label="会议视频" :span="2">
              <video 
                :src="currentMeeting.videoUrl" 
                controls 
                style="max-width: 100%; max-height: 400px;"
              />
            </el-descriptions-item>
          </el-descriptions>

          <div v-if="currentMeeting.coverImage" class="detail-cover">
            <h3>会议封面</h3>
            <el-image
              :src="currentMeeting.coverImage"
              :preview-src-list="[currentMeeting.coverImage]"
              fit="contain"
            />
          </div>

          <div v-if="currentMeeting.files?.length" class="detail-files">
            <h3>会议文件</h3>
            <meeting-file-list
              :files="currentMeeting.files"
              @download="handleFileDownload"
            />
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 视频对话框 -->
    <el-dialog
      v-model="videoDialogVisible"
      title="会议视频"
      width="70%"
      @close="currentVideoUrl = ''"
    >
      <video
        v-if="currentVideoUrl"
        :src="currentVideoUrl"
        controls
        style="width: 100%; max-height: 70vh;"
      />
    </el-dialog>

    <!-- 文件对话框 -->
    <el-dialog
      v-model="fileDialogVisible"
      title="会议文件"
      width="60%"
    >
      <div v-if="currentMeetingFiles && currentMeetingFiles.length" class="meeting-files">
        <el-table :data="currentMeetingFiles" style="width: 100%">
          <el-table-column prop="name" label="文件名" min-width="200" />
          <el-table-column prop="size" label="文件大小" width="120">
            <template #default="{ row }">
              {{ formatFileSize(row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" width="180" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="primary" link @click="downloadFile(row)">
                <el-icon><Download /></el-icon>下载
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="no-files">
        <el-empty description="暂无相关文件" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '../utils/date'
import {
  MeetingType,
  MeetingStatus,
  Meeting,
  getMeetingList,
  createMeeting,
  updateMeeting,
  deleteMeeting,
  updateMeetingStatus,
  batchDeleteMeetings,
  checkMeetingStatus,
  batchUpdateMeetingStatus,
  MeetingFormData,
  MeetingQuery,
  exportMeetingData,
  publishMeeting,
  cancelMeeting,
  getMeetingDetail,
  MeetingFile
} from '@/api/meeting'
import MeetingStatusTag from '@/components/meeting/MeetingStatusTag.vue'
import MeetingForm from '@/components/meeting/MeetingForm.vue'
import MeetingFileList from '@/components/meeting/MeetingFileList.vue'
import {
  Plus,
  Search,
  Refresh,
  Delete,
  Edit,
  CircleClose,
  Download,
  View,
  Star,
  Upload
} from '@element-plus/icons-vue'
import { ElImageViewer } from 'element-plus'

const meetingTypes = [
  { label: '主论坛', value: MeetingType.MAIN },
  { label: '平行会议', value: MeetingType.PARALLEL },
  { label: '科普论坛', value: MeetingType.SCIENCE },
  { label: '新品发布', value: MeetingType.PRODUCT },
  { label: '生态合作论坛', value: MeetingType.ECOLOGY }
]

const loading = ref(false)
const meetingList = ref<Meeting[]>([])
const selectedMeetings = ref<Meeting[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentMeeting = ref<Meeting>()

// 添加新的响应式变量
const videoDialogVisible = ref(false)
const currentVideoUrl = ref('')

// 添加文件相关的响应式变量
const fileDialogVisible = ref(false)
const currentMeetingFiles = ref<MeetingFile[]>([])

const filterForm = reactive({
  type: MeetingType.ALL,
  status: null as MeetingStatus | null,
  dateRange: [] as string[],
  keyword: '',
  id: undefined as string | undefined
})

const getMeetingTypeLabel = (type: MeetingType) => {
  const found = meetingTypes.find(t => t.value === type)
  return found ? found.label : '未知类型'
}

// 添加定时检查状态的功能
let statusCheckTimer: number | null = null

// 检查并更新会议状态
const checkAndUpdateStatus = async () => {
  if (!meetingList.value.length) return

  try {
    const updatedMeetings = await batchUpdateMeetingStatus(meetingList.value)
    // 如果有状态更新，只更新本地数据，不重新请求
    if (updatedMeetings) {
      meetingList.value = meetingList.value.map(meeting => {
        const updatedMeeting = updatedMeetings.find(m => m.id === meeting.id)
        return updatedMeeting || meeting
      })
    }
  } catch (error) {
    console.error('更新会议状态失败:', error)
  }
}

const loadMeetingList = async () => {
  loading.value = true
  try {
    const params: Record<string, any> = {
      page: currentPage.value,
      size: pageSize.value,
      type: filterForm.type === MeetingType.ALL ? undefined : filterForm.type,
      status: filterForm.status || undefined,
      name: filterForm.keyword || undefined,
      id: filterForm.id || undefined
    }

    if (filterForm.dateRange?.length === 2 && 
        filterForm.dateRange[0] && 
        filterForm.dateRange[1]) {
      params.dateRange = `${filterForm.dateRange[0]},${filterForm.dateRange[1]}`
    }
    
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key];
      }
    });

    const res = await getMeetingList(params as MeetingQuery) as {
      current_data: Meeting[];
      total_record: number;
    }
    
    // 处理数据映射
    meetingList.value = res.current_data.map((item: any) => {
      // 解析议程
      let parsedAgenda;
      try {
        parsedAgenda = item.agenda ? JSON.parse(item.agenda) : undefined;
        // 处理时间格式
        if (parsedAgenda) {
          parsedAgenda = parsedAgenda.map((agendaItem: any) => ({
            ...agendaItem,
            startTime: new Date(agendaItem.startTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
            endTime: new Date(agendaItem.endTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
          }));
        }
      } catch (e) {
        console.error('解析议程失败:', e);
        parsedAgenda = undefined;
      }

      const meeting: Meeting = {
        id: String(item.id),
        name: item.name,
        type: item.type,
        status: item.status,
        begin: item.begin,
        end: item.end || item.begin,
        description: item.description,
        coverImage: item.coverImage,
        location: item.location || '',
        isOnline: item.online === undefined ? true : Boolean(item.online),
        agenda: parsedAgenda ? JSON.stringify(parsedAgenda) : '[]',
        files: item.files || null,
        browseCount: String(item.browseCount || 0),
        goodCount: String(item.goodCount || 0),
        maxAttendees: item.maxAttendees,
        currentAttendees: item.currentAttendees,
        videoUrl: item.video,
        timeRange: item.begin && item.end ? `${item.begin},${item.end}` : `${item.begin},${item.begin}`
      };

      return meeting;
    });
    
    total.value = res.total_record
  } catch (error) {
    console.error('获取会议列表失败:', error)
    ElMessage.error('获取会议列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadMeetingList()
}

const resetSearch = () => {
  filterForm.type = MeetingType.ALL
  filterForm.status = null
  filterForm.dateRange = []
  filterForm.keyword = ''
  handleSearch()
}

const handleSelectionChange = (selection: Meeting[]) => {
  selectedMeetings.value = selection
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadMeetingList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadMeetingList()
}

const handleAdd = () => {
  dialogType.value = 'add'
  currentMeeting.value = undefined
  dialogVisible.value = true
}

const handleEdit = (row: Meeting) => {
  dialogType.value = 'edit'
  // 确保 isOnline 字段正确解析
  currentMeeting.value = {
    ...row,
    isOnline: true  // 根据你的描述，这个会议是线上的，所以直接设置为 true
  }
  dialogVisible.value = true
}

const handleViewDetail = (row: Meeting) => {
  currentMeeting.value = row
  detailDialogVisible.value = true
}

const handleDelete = async (row: Meeting) => {
  try {
    await ElMessageBox.confirm('确定要删除该会议吗？', '提示', {
      type: 'warning'
    })
    await deleteMeeting(row.id)
    ElMessage.success('删除成功')
    loadMeetingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchDelete = () => {
  if (!selectedMeetings.value.length) {
    ElMessage.warning('请选择要删除的会议')
    return
  }

  ElMessageBox.confirm(
    `确认删除选中的 ${selectedMeetings.value.length} 个会议吗？此操作不可恢复！`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      const ids = selectedMeetings.value.map(meeting => String(meeting.id))
      await batchDeleteMeetings(ids)
      ElMessage.success('批量删除成功')
      selectedMeetings.value = []
      loadMeetingList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    } finally {
      loading.value = false
    }
  })
}

const handleCancel = async (row: Meeting) => {
  try {
    await ElMessageBox.confirm('确定要取消该会议吗？', '提示', {
      type: 'warning'
    })
    await cancelMeeting(row.id)
    ElMessage.success('会议已取消')
    loadMeetingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

const handleSubmit = async (formData: Partial<Meeting>) => {
  try {
    loading.value = true
    if (currentMeeting.value) {
      // 编辑会议，直接更新
      await updateMeeting(currentMeeting.value.id, formData)
      ElMessage.success('会议更新成功')
    } else {
      // 新增会议
      // MeetingForm组件已经处理了文件上传，这里只需要创建会议
      
      // 确保数据符合MeetingFormData接口
      const meetingFormData: MeetingFormData = {
        name: formData.name || '',
        type: formData.type || MeetingType.MAIN,
        begin: formData.begin || '',
        end: formData.end || '',
        timeRange: formData.begin && formData.end ? `${formData.begin},${formData.end}` : undefined,
        location: formData.location || '',
        description: formData.description || '',
        isOnline: formData.isOnline !== undefined ? formData.isOnline : true,
        agenda: formData.agenda,
        coverImage: formData.coverImage,
        videoUrl: formData.videoUrl,
        files: formData.files || []
      }
      
      // 创建会议
      await createMeeting(meetingFormData)
      ElMessage.success('会议创建成功')
    }
    dialogVisible.value = false
    loadMeetingList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败: ' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    loading.value = false
  }
}

const handleFileDownload = () => {
  loadMeetingList() // 刷新列表以更新下载次数
}

const handleExport = async () => {
  if (!selectedMeetings.value.length) {
    ElMessage.warning('请选择要导出的会议')
    return
  }

  try {
    loading.value = true
    const ids = selectedMeetings.value.map(meeting => String(meeting.id))
    const response = await exportMeetingData(ids)
    
    // 直接使用响应的 Blob
    if (response instanceof Blob) {
      const downloadUrl = window.URL.createObjectURL(response)
      const downloadLink = document.createElement('a')
      downloadLink.href = downloadUrl
      downloadLink.download = '会议数据.xlsx'
      document.body.appendChild(downloadLink)
      downloadLink.click()
      document.body.removeChild(downloadLink)
      window.URL.revokeObjectURL(downloadUrl)
      ElMessage.success('导出成功')
    } else {
      throw new Error('导出失败：响应格式不正确')
    }
  } catch (error) {
    console.error('导出会议数据失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let i = 0
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024
    i++
  }
  return Math.round(size * 100) / 100 + ' ' + units[i]
}

// 查看文件列表
const handleViewFiles = async (row: Meeting) => {
  try {
    loading.value = true
    // 通过 API 获取最新的会议详情
    const response = await getMeetingDetail(row.id)

    console.log("文件response",response);

    if (response && Array.isArray(response.files)) {
      currentMeetingFiles.value = response.files
      fileDialogVisible.value = true
    } else {
      currentMeetingFiles.value = []
      fileDialogVisible.value = true
      ElMessage.info('该会议暂无关联文件')
    }
  } catch (error) {
    console.error('获取会议文件失败:', error)
    ElMessage.error('获取会议文件失败')
  } finally {
    loading.value = false
  }
}

// 下载文件
const downloadFile = (file: MeetingFile) => {
  if (!file.url) {
    ElMessage.warning('文件链接无效')
    return
  }
  
  // 创建一个临时下载链接
  const downloadLink = document.createElement('a')
  downloadLink.href = file.url
  downloadLink.target = '_blank'
  downloadLink.download = file.name || '未命名文件'
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
}

// 修改发布会议的处理函数
const handlePublish = async (row: Meeting) => {
  try {
    await ElMessageBox.confirm('确定要发布该会议吗？', '提示', {
      type: 'warning'
    })
    await publishMeeting(row.id)
    ElMessage.success('发布成功')
    loadMeetingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

// 启动定时检查
const startStatusCheck = () => {
  // 改为每小时检查一次
  statusCheckTimer = window.setInterval(checkAndUpdateStatus, 60 * 60 * 1000)
}

// 停止定时检查
const stopStatusCheck = () => {
  if (statusCheckTimer) {
    clearInterval(statusCheckTimer)
    statusCheckTimer = null
  }
}

const previewImage = (url: string) => {
  ElImageViewer.open({
    urlList: [url],
    onClose: () => {
      ElImageViewer.close()
    }
  })
}

// 修改视频查看处理函数
const handleViewVideo = (row: Meeting) => {
  if (row.videoUrl) {
    currentVideoUrl.value = row.videoUrl
    videoDialogVisible.value = true
  }
}

onMounted(() => {
  loadMeetingList()
  // 延迟1秒后开始状态检查
  setTimeout(() => {
    startStatusCheck()
  }, 1000)
})

onBeforeUnmount(() => {
  stopStatusCheck()
})

// 导出所有需要的方法和变量
defineExpose({
  handleSearch,
  handleAdd,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  handleExport,
  handleCancel,
  handleSubmit,
  handleFileDownload,
  handleViewDetail,
  handleViewVideo,
  handleViewFiles,
  handleSelectionChange,
  handleSizeChange,
  handleCurrentChange,
  resetSearch
})
</script>

<style lang="scss" scoped>
@import '@/styles/common.scss';

.meeting-management {
  .meeting-detail {
    padding: 20px;

    .detail-header {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      gap: 16px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }
    }

    .detail-cover {
      margin-top: 20px;

      h3 {
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .el-image {
        max-width: 100%;
        max-height: 400px;
        border-radius: 8px;
      }
    }

    .detail-files {
      margin-top: 20px;

      h3 {
        margin-bottom: 16px;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    pre {
      white-space: pre-wrap;
      word-wrap: break-word;
      margin: 0;
      font-family: inherit;
      background-color: #f5f7fa;
      padding: 12px;
      border-radius: 4px;
      color: #606266;
    }

    :deep(.el-descriptions) {
      margin-top: 20px;

      .el-descriptions__title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .el-descriptions__label {
        color: #606266;
        font-weight: 600;
      }

      .el-descriptions__content {
        color: #303133;
      }
    }
  }

  .count-item {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    color: #606266;

    .el-icon {
      font-size: 16px;
    }
  }
}

.video-dialog {
  .el-message-box__message {
    padding: 0;
    margin: 0;
  }
  
  video {
    display: block;
    width: 100%;
    max-height: 70vh;
    margin: 0;
  }
}

.cover-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}

.agenda-list {
  .agenda-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 4px 0;
    border-bottom: 1px solid #EBEEF5;
    
    &:last-child {
      border-bottom: none;
    }

    .agenda-time {
      color: #409EFF;
      font-size: 13px;
      white-space: nowrap;
    }

    .agenda-title {
      font-weight: 500;
      white-space: nowrap;
    }

    .agenda-speaker {
      color: #606266;
      font-size: 13px;
      white-space: nowrap;
    }

    .agenda-description {
      color: #909399;
      font-size: 13px;
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style> 